package com.ml.shs.service;

import com.ml.shs.entity.Goods;
import com.ml.shs.repository.GoodsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class GoodsService {

    @Autowired
    GoodsRepository goodsRepository;

    @Autowired
    HttpSession session;

    public List<Goods> getList(String classifyId) {
        List<Goods> goodsList = new ArrayList<Goods>();
        if ("".equals(classifyId)) {
            goodsList = goodsRepository.findGoodsList();
        } else {
            goodsList = goodsRepository.findGoodsListByClassify(classifyId);
        }
        return goodsList;
    }

    public List<Goods> getListByUser(String userId){
        return goodsRepository.findAllByCreaterId(userId);
    }

    public void save(Goods goods) {
        Object userId  = session.getAttribute("userId");
        if(userId != null){
            goods.setCreaterId(userId.toString());
        }
        goodsRepository.save(goods);
    }

    public void completion(String goodsId) throws Exception{
        Optional<Goods> op = goodsRepository.findById(goodsId);
        Goods goods = op.get();
        if (goods != null) {
            checkCreater(goods);
            goods.setState("1");
            goodsRepository.save(goods);
        }
    }

    public void delete(String id) throws Exception{
        Optional<Goods> op = goodsRepository.findById(id);
        Goods goods = op.get();
        if (goods != null) {
            checkCreater(goods);
            goods.setState("-1");
            goodsRepository.save(goods);
        }
    }

    public void checkCreater(Goods goods) throws Exception{
        Object userId  = session.getAttribute("userId");
        if(userId != null){
            if(!userId.toString().equals(goods.getCreaterId())){
                throw new Exception("没有操作权限");
            }
        }
    }
}
